package mobi.greenplate.theweb.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import mobi.greenplate.theweb.persistence.AppEngineEntityManagerFactory.EmTemplate;

/**
 *
 * @author dmakariev
 */
public class UnonwedLoader {

    private UnonwedLoader() {
    }

    //http://gae-java-persistence.blogspot.com/2009/10/executing-batch-gets.html
    public static <T> List<T> loadByIdList(final Class<T> clazz, final List<Long> keys) {

        return AppEngineEntityManagerFactory.inTransacion(new EmTemplate<List<T>>() {

            public List<T> execute(EntityManager em) {
                Query q = em.createQuery("select from " + clazz.getName() + " where id = :ids");
                q.setParameter("ids", keys);
                List<T> result = q.getResultList();
                result.size();
                return result;
            }
        });
    }

    public static <T> T loadById(final Class<T> clazz, final Long id) {
        return AppEngineEntityManagerFactory.inTransacion(new EmTemplate<T>() {

            public T execute(EntityManager em) {
                return em.find(clazz, id);
            }
        });
    }

    public static <T> List<T> mappedBy(final Class<T> clazz, final String columnName, final Long id) {
        return AppEngineEntityManagerFactory.inTransacion(new EmTemplate<List<T>>() {

            public List<T> execute(EntityManager em) {
                Query q = em.createQuery("select from " + clazz.getName() + " where " + columnName + " = :id");
                q.setParameter("id", id);
                List<T> result = q.getResultList();
                result.size();
                return result;
            }
        });        
    }
}
